# -*- coding: utf-8 -*-
from zope.component import getAdapters
from zope.contentprovider.provider import ContentProviderBase
from zope.contentprovider.interfaces import BeforeUpdateEvent
from zope.interface import implements
from zope.location.interfaces import ILocation
from zope.event import notify

from pargo.viewlet.interfaces import IViewletManager, IViewlet

class ViewletManagerBase(ContentProviderBase):
    """
    The Viewlet Manager.
    """
    implements(IViewletManager)
    
    def __init__(self, context, request, view):
        super(ViewletManagerBase, self).__init__(context, request, view)
        self.__updated = False
    
    def update(self):
        """
        See zope.contentprovider.interfaces.IContentProvider
        """
        self.__updated = True

        viewlets = getAdapters((self.context, self.request, self.__parent__, self), IViewlet)

        # Just use the viewlets from now on
        self.viewlets = []
        for name, viewlet in viewlets:
            if ILocation.providedBy(viewlet):
                viewlet.__name__ = name
            self.viewlets.append(viewlet)
        self._updateViewlets()

    def _updateViewlets(self):
        """
        Calls update on all viewlets and fires events
        """
        for viewlet in self.viewlets:
            notify(BeforeUpdateEvent(viewlet, self.request))
            viewlet.update()

    def render(self):
        """
        See zope.contentprovider.interfaces.IContentProvider
        """
        return u'\n'.join([viewlet.render() for viewlet in self.viewlets])
